//
//  TimeRemainLabel.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2024/9/4.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
 
class TimeRemainLabel: UILabel {
   
    var normalText = ""
    var endDate:String?
    
    // 定时器
    private var timer: Timer?
    
    // 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 初始化设置
        self.textAlignment = .center
        self.textColor = .black
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // 从编码中初始化时也可以设置一些默认值
    }
    
    // 开始更新定时器
    func startUpdating() {
        // 停止已存在的定时器
        timer?.invalidate()
        
        // 创建一个新的定时器每秒调用一次
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeShow), userInfo: nil, repeats: true)
    }
    
    @objc func updateTimeShow() {
        self.text = caculateDif(normalText: normalText, endDate: endDate)
    }
    func caculateDif(normalText:String,endDate:String?) -> String {
        if let target = endDate {
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            
            let dateFormatter2 = DateFormatter()
            dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
            let dateFormatter3 = DateFormatter()
            dateFormatter3.dateFormat = "yyyy-MM-dd"
            
            var endDDD:Date?
            if let endD = dateFormatter.date(from: target) {
                endDDD = endD
            }
            
            if let endD2 = dateFormatter2.date(from: target) {
                endDDD = endD2
            }
            
            if let endD3 = dateFormatter3.date(from: target) {
                endDDD = endD3
            }
            if endDDD.isSome {
              
              return updateTimeDifference(normalText: normalText, target: endDDD!)
              
            } else {
                return normalText
            }
            
        } else {
            return normalText
        }
        
    }
    // 更新时间差的方法
    @objc private func updateTimeDifference(normalText:String,target:Date) -> String {
        
        // 计算时间差
        let now = Date()
        let difference = target.timeIntervalSince(now)
        
        // 格式化时间差显示
        var text = ""
        if difference > 0 {
            let seconds = Int(difference)
            let minutes = seconds / 60
            let hours = minutes / 60
           
                return  String(format: "预计剩余 %02d时%02d分%02d秒", hours, minutes % 60, seconds % 60)

            
            
        } else {
            //            text = "00:00:00" // 时间已过
            return   normalText
        }
      
    }
}
